package com.hanbang.chu_xing_gao_zhao.module;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hanbang.chu_xing_gao_zhao.application.HttpInterfaces;
import com.hanbang.chu_xing_gao_zhao.base.BaseActivity;
import com.hanbang.chu_xing_gao_zhao.myview.Singleness;
import com.hanbang.chu_xing_gao_zhao.myview.Singleness.OnClickCallback;
import com.hanbang.chu_xing_gao_zhao.utils.EditHelper;
import com.hanbang.chu_xing_gao_zhao.utils.MyRequestCallBack;
import com.hanbang.chu_xing_gao_zhao.utils.MySharedPreferences;
import com.hanbang.chu_xing_gao_zhao.utils.MyToast;
import com.hanbang.chu_xing_gao_zhao.view_dynamic.DynamicActivity;
import com.hanbang.cxgz_2.R;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * 忘记密码
 */
public class ForgetPasswordActivity extends BaseActivity {

    /**
     * 编辑助手
     */
    private EditHelper editHelper = new EditHelper(this);

    /**
     * 验证码按钮倒计时 总时长和间隔时长，默认为60秒
     */
    private long totalTime = 60000, intervalTime = 1000;

    /**
     * 发送验证码
     */
    private TextView sendVerificationCode;

    /**
     * 验证码记录
     */
    private String verificationCode = "11";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.forget_password);
        initView();
        setOnClickListener();
        SinglenessButton();
    }

    /**
     * 初始化view
     */
    private void initView() {
        // 设置顶部的标题
        setBackArrows(findViewById(R.id.bar_top_conver_classify_back));
        setTitleMore(View.VISIBLE, View.INVISIBLE, "修改密码", null, null, null);


        sendVerificationCode = (TextView) findViewById(R.id.register_send_verification);

        editHelper.setEditText((EditText) findViewById(R.id.phone), // 加入手机号
                (EditText) findViewById(R.id.verificationCode),// 加入验证码
                (EditText) findViewById(R.id.password), // 加入密码
                (EditText) findViewById(R.id.password2));// 加入确认密码

        // 添加提示文本
        editHelper.setHintText("请正确输入手机号", "请输入短信验证码", "请输入最少6位密码", "请输入最少6位确认密码");

        // 添加最小值
        editHelper.setHintMinNumber(11, 1, 6, 6);


    }

    /**
     * 单选按钮的监听，与取值
     */
    private void SinglenessButton() {


    }

    /**
     * 设置点击事件
     */
    private void setOnClickListener() {
        findViewById(R.id.register_next).setOnClickListener(onClickListener);
        sendVerificationCode.setOnClickListener(onClickListener);


    }

    /**
     * 监听处理
     */
    private OnClickListener onClickListener = new OnClickListener() {
        Intent intent = new Intent();

        @Override
        public void onClick(View v) {
            switch (v.getId()) {

                // 确认自发密码
                case R.id.register_next:

                    if (!verificationCode.equals(((EditText) findViewById(R.id.verificationCode)).getText().toString())) {
                        MyToast.show(ForgetPasswordActivity.this, "验证码不匹配", Toast.LENGTH_LONG);
                        break;
                    }

                    if ((((EditText) findViewById(R.id.password)).getText().toString().trim()).equals("")
                            || (((EditText) findViewById(R.id.password2)).getText().toString().trim()).equals("")) {
                        MyToast.show(ForgetPasswordActivity.this, "密码不能为空", Toast.LENGTH_LONG);
                        break;
                    }

                    if (!((EditText) findViewById(R.id.password)).getText().toString().trim()
                            .equals(((EditText) findViewById(R.id.password2)).getText().toString().trim())) {
                        MyToast.show(ForgetPasswordActivity.this, "两次密码不一致", Toast.LENGTH_LONG);

                        break;
                    }

                    updataPassword();
                    break;

                // 获取验证码
                case R.id.register_send_verification:

                    sendVerificationCode();
                    break;


                default:
                    break;
            }
        }
    };

    /**
     * 更改密码
     * <p/>
     * telphone：手机号码
     * code:验证码
     * password0：密码
     * password1：密码
     */
    private void updataPassword() throws IndexOutOfBoundsException {
        final ArrayList<String> res = editHelper.getText();

        RequestParams params = new RequestParams();

        params.addBodyParameter("telphone", res.get(0));
        params.addBodyParameter("code", res.get(1));
        params.addBodyParameter("password0", res.get(2));
        params.addBodyParameter("password1", res.get(3));

        httpUtils.send(HttpMethod.POST, HttpInterfaces.ForgetPassword, params, new MyRequestCallBack<String>(this,
                "") {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                super.onSuccess(responseInfo);
                try {
                    JSONObject json = new JSONObject(responseInfo.result);
                    int status = json.getInt("Result");
                    if (status == 0) {
                        MySharedPreferences.setSharedPreferencesKeyAndValue(ForgetPasswordActivity.this,
                                MySharedPreferences.USER_DATA, "password",
                                ((EditText) findViewById(R.id.password2)).getText().toString());

                        try {
                            userData.setPassword(res.get(3));
                            dbUtils.saveOrUpdate(userData);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }

                        // 跳转到登录界面
                        Intent intent = new Intent(ForgetPasswordActivity.this, DynamicActivity.class);
                        startActivity(intent);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    MyToast.show(ForgetPasswordActivity.this, "修改失败", Toast.LENGTH_LONG);
                }
            }
        });
    }

    /**
     * 手机发送验证码
     *
     * @throws IndexOutOfBoundsException
     */
    private void sendVerificationCode() throws IndexOutOfBoundsException {

        final ArrayList<String> res = editHelper.getText();
        // 号码不为空并且长度为11位
        if (res.get(0) == null || res.get(0).equals("") || res.get(0).length() < 11) {
            MyToast.show(ForgetPasswordActivity.this, "请正确输入手机号！", Toast.LENGTH_LONG);
            return;
        }
        // 发送
        httpUtils.send(HttpMethod.GET, HttpInterfaces.ForgetPasswordCode + "&telphone=" + res.get(0),
                new MyRequestCallBack<String>(this, "正在发送验证码...") {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        super.onSuccess(responseInfo);
                        try {
                            JSONObject json = new JSONObject(responseInfo.result);

                            int status = json.getInt("Result");
                            if (status == 0) {
                                countDownTimer.start();

                            }

                            MyToast.show(ForgetPasswordActivity.this, json.getString("Msg"), Toast.LENGTH_LONG);
                            if (!verificationCode.equals("")) {
                                // 验证码清空
                                verificationCode = "";
                                // 添加新的验证码
                                verificationCode = json.getString("code");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 记录当下剩余时间
     */
    CountDownTimer countDownTimer = new CountDownTimer(totalTime, intervalTime) {
        @Override
        public void onFinish() {// 计时完毕时触发
            sendVerificationCode.setText("重新发送");
            sendVerificationCode.setEnabled(true);
            // authCodeButton.setClickable(true);
        }

        @Override
        public void onTick(long currentTime) {// 计时过程显示
            // authCodeButton.setClickable(false);
            sendVerificationCode.setEnabled(false);
            sendVerificationCode.setText(currentTime / 1000 + "秒");
        }
    };

    @Override
    protected void onResume() {


        super.onResume();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }
}
